import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../index.dart';

import 'package:device_info_plus/device_info_plus.dart';
import 'dart:io';
import 'package:amap_map_fluttify/amap_map_fluttify.dart';

// 提供五套可选主题色
const _themes = <MaterialColor>[
  Colors.blue,
  Colors.blueGrey,
  Colors.teal,
  Colors.green,
  Colors.red,
];

// height of the 'Gallery' header
const double galleryHeaderHeight = 64;

// The font size delta for headline4 font.
const double desktopDisplay1FontDelta = 16;

// The width of the settingsDesktop.
const double desktopSettingsWidth = 520;

// Sentinel value for the system text scale factor option.
const double systemTextScaleFactorOption = -1;

enum DarkModelOption {
  darkModelOptionSystem,
  darkModelOptionDark,
  darkModelOptionLight,
}

const int systemTimeDilationOption = 1;

// The splash page animation duration.
const splashPageAnimationDurationInMilliseconds = 300;

// The desktop top padding for a page's first header (e.g. Gallery, Settings)
const firstHeaderDesktopTopPadding = 5.0;

class Global {
  static late SharedPreferences _prefs;
  static Profile profile = Profile();
  static String? deviceInfo;

  // 网络缓存对象
  static NetCache netCache = NetCache();

  // 可选的主题列表
  static List<MaterialColor> get themes => _themes;

  // 是否为release版 发布版本时候 需要修改为true
  // 使用kReleaseMode会导致测试版不能修改域名
  static bool get isRelease => false;

  static SharedPreferences getPrefs() {
    return _prefs;
  }

  // 初始化全局信息，会在APP启动时执行
  static Future init() async {
    WidgetsFlutterBinding.ensureInitialized();
    _prefs = await SharedPreferences.getInstance();
    String? _profile = _prefs.getString("profile");

    if (_profile != null) {
      Debug.info("--$_profile");
      try {
        profile = Profile.fromJson(jsonDecode(_profile));
      } catch (e) {
        print(e);
      }
    } else {
      // 默认主题索引为0，代表蓝色
      profile = Profile()
        ..theme = 0
        ..textScaling = systemTextScaleFactorOption
        ..darkMode = DarkModelOption.darkModelOptionSystem.index
        ..timeDilation = systemTimeDilationOption
        ..isUseProxy = false
        ..proxy = HttpGo.proxyUrl
        ..apiDomain =
            isRelease ? HttpGo.releaseApiDomain : HttpGo.devApiDomain;
    }

    // 如果没有缓存策略，设置默认缓存策略
    profile.cache = profile.cache ?? CacheConfig()
      ..enable = false
      ..maxAge = 3600
      ..maxCount = 100;
    final deviceInfoPlugin = DeviceInfoPlugin();
    if (kIsWeb) {
      WebBrowserInfo webBrowserInfo = await deviceInfoPlugin.webBrowserInfo;
      deviceInfo = webBrowserInfo.userAgent;
      Debug.info('Running on ${webBrowserInfo.userAgent}');
    } else {
      if (Platform.isAndroid) {
        AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
        deviceInfo = androidInfo.model;
        Debug.info('Running on ${androidInfo.model}'); // e.g. "Moto G (4)"
      } else if (Platform.isIOS) {
        IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
        deviceInfo = iosInfo.utsname.machine;
        Debug.info('Running on ${iosInfo.utsname.machine}'); // e.g. "iPod7,1"
      }
    }

    //初始化网络请求相关配置
    HttpGo.init();


    // ///建议在APP首次启动或者进行弹窗进行隐私声明时，根据用户设置
    // ///
    // /// [hasContains] 隐私权政策是否包含高德开平隐私权政策
    // ///
    // ///[hasShow] 隐私权政策是否弹窗展示告知用户
    // ///
    // ///[hasAgree] 隐私权政策是否已经取得用户同意
    // static const AMapPrivacyStatement amapPrivacyStatement =
    // AMapPrivacyStatement(hasContains: true, hasShow: true, hasAgree: true);
    //
    // ///在创建地图时设置privacyStatement属性
    // final AMapWidget map = AMapWidget(
    //   ///必须正确设置的合规隐私声明，否则SDK不会工作，会造成地图白屏等问题。
    //   privacyStatement: ConstConfig.amapPrivacyStatement,
    // );
    // AMapPrivacyStatement(hasContains: true, hasShow: true, hasAgree: true);
    await enableFluttifyLog(false);
    await AmapSearch.instance.updatePrivacyAgree(true);
    await AmapSearch.instance.updatePrivacyShow(true);
    await AmapService.instance.init(
      iosKey: ConstConfig.iOSAMapKey,
      androidKey: ConstConfig.androidAMapKey,
    );
    // await AmapCore.init(ConstConfig.iOSAMapKey);
  }

  // 持久化Profile信息
  static saveProfile() =>
      _prefs.setString("profile", jsonEncode(profile.toJson()));

  static double textScaleFactor(BuildContext context) {
    var textScalingModel = Provider.of<TextScalingModel>(context);
    if (textScalingModel.textScaling == systemTextScaleFactorOption) {
      return MediaQuery.of(context).textScaleFactor;
    } else {
      return (textScalingModel.textScaling as double);
    }
  }
}

// Applies text GalleryOptions to a widget
class GlobalStyle extends StatelessWidget {
  const GlobalStyle({Key? key, required this.child}) : super(key: key);

  final Widget child;

  @override
  Widget build(BuildContext context) {
    final textScaleFactor = Global.textScaleFactor(context);

    return MediaQuery(
      data: MediaQuery.of(context).copyWith(
        textScaleFactor: textScaleFactor,
      ),
      child: child,
    );
  }
}

// Applies text GalleryOptions to a widget
class BackgroundStyleWidget extends StatelessWidget {
  const BackgroundStyleWidget({Key? key, required this.child})
      : super(key: key);

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Theme.of(context).colorScheme.background,
      child: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage(
                'images/global_background.png',
              ),
              fit: BoxFit.fill),
        ),
        child: child,
      ),
    );
  }
}
